package com.lh.learning.mq.controller;

import org.apache.rocketmq.client.producer.SendCallback;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.spring.core.RocketMQLocalRequestCallback;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/rocketmq")
public class RocketMqController {

    @Autowired
    private RocketMQTemplate rocketMQTemplate;

    @PostMapping("/send")
    public void sendMsg(@RequestBody String msg) throws InterruptedException {
//        rocketMQTemplate.sendMessageInTransaction("topic-1", MessageBuilder.withPayload(msg).build(), null);
        rocketMQTemplate.sendAndReceive("topic-2", msg, new RocketMQLocalRequestCallback() {
            @Override
            public void onSuccess(Object message) {
                System.out.println(message);
            }

            @Override
            public void onException(Throwable e) {

            }
        });
    }

    @PostMapping("/async/send")
    public void asyncSendMsg(@RequestBody String msg) {
        rocketMQTemplate.asyncSend("topic-2", msg, new SendCallback() {
            @Override
            public void onSuccess(SendResult sendResult) {
                System.out.printf("异步消息发送成功，result=%s %n", sendResult);
            }

            @Override
            public void onException(Throwable throwable) {
                System.out.printf("异步消息发送异常，result=%s %n", throwable);
            }
        });
    }
}
